//EZblu 主客服
import React, { useState,useEffect } from 'react'
import {withRouter} from "react-router-dom"
import {Bottom, InputItem,Button} from "antd-mobile"
import "./onlineSystemService.scss"
import WebSocket from "../WebSocket/Index";
import GoEasy from 'goeasy'
import ReactDom from 'react-dom';
import SockJsClient from 'react-stomp';
import Input from 'antd-mobile/lib/input-item/Input';
import axios from 'axios'
import Header from '../../assets/img/katong.jpg'
import Kehu from '../../assets/img/110.jpg'
const randomstring = require('randomstring');
var goeasy  = GoEasy.getInstance({
    host:"singapore.goeasy.io",  //若是新加坡东南亚区域：singapore.goeasy.io // 中国区域hangzhou.goeasy.io
    appkey:"BC-61f166d35a9a4283a65a27be605eec34",
    modules:['pubsub']//根据需要，传入‘pubsub’或'im’，或数组方式同时传入
});

const OnlineSystemService = ()=> {

    const [ message, setMessage ] = useState([])
    const [ value, setValue ] = useState("")
    const [mes,setMess] = useState([])
    const [txt,setTxt] = useState("")
    const [user,setUser] = useState({})

     useEffect(() => {
        document.title = "EZblu客服"
        //getUserName()
        startOnclick()
        getMessage();
    })
    
    //断开链接
    function clearOnclick(){
         //断开连接
        goeasy.disconnect({
            onSuccess: function(){
                console.log("断开链接成功")
            },
            onFailed: function(error){
                console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
            }
        });
    }

    //启动链接
    function startOnclick(){
        //建立连接
        goeasy.connect({
            id:"001", //pubsub选填，im必填
            data:{"avatar":"/www/xxx.png","nickname":"Neo"}, //必须是一个对象，pubsub选填，im必填，用于上下线提醒和查询在线用户列表时，扩展更多的属性
            onSuccess: function () {  //连接成功
            console.log("连接成功") //连接成功
            },
            onFailed: function (error) { //连接失败
            console.log("连接失败 code:"+error.code+ ",error:"+error.content);
            },
            onProgress:function(attempts) { //连接或自动重连中
            console.log("自动重连中", attempts);
            }
        });
        
    }

    //获取用户所在ip地址地理位置
    async function getUserName(){
        //数据库获取用户的信息,username名称
        
        const response = await axios.get("http://localhost:9999/api/user/getid/1");
        setUser(response)
        console.log(response)
    }

    //接收消息
   function getMessage(){
        
        var pubsub = goeasy.pubsub;
        pubsub.subscribe({
            channel: "ezblu",//替换为您自己的channel
            onMessage: function (message) {
                console.log("Channel:" + message.channel + " content:" + message.content); 
                setMess([...mes,{"msg":message.content,
                "Channel":message.channel
                 }])
            },
            onSuccess: function () {
                console.log("Channel订阅成功。");
            },
            onFailed: function (error) {
                console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" + error.content)
            }
        });
        console.log("获取参数")
    }

    //发送消息
    function sendMessages(){
        var pubsub = goeasy.pubsub;
        pubsub.publish({
            channel: "account1",//替换为您自己的channel
            message: txt,//替换为您想要发送的消息内容
            onSuccess:function(){
                console.log("消息发布成功。");
                setMess([...mes,{"msg":txt,
                "Channel":"account1"
                 }])
            },
            onFailed: function (error) {
                console.log("消息发送失败，错误编码："+error.code+" 错误信息："+error.content);
            }
        });
        setTxt("")
        
    }

        return (
            <div style={{width:"100%",position:"relative"}}>
            <div style={{textAlign:"center"}}>在线客服</div>
            <div style={{width:"100%",height:500,background:"#fff",borderRadius:20}}>{mes.map((v,i)=>{
                return (
                    <div key={i}> 
                        <div> 
                          {v.Channel !== "ezblu"?
                          <div style={{marginTop:20}}> 
                                 <div style={{width:"100%",borderRadius:40,display:"flex",flexDirection:"row"}}>
                                    <div style={{width:40,height:40,borderRadius:40}}>
                                        <img style={{width:"100%",height:"100%"}} src={Header}></img>
                                    </div>

                                     <div>
                                            <h4 style={{color:"rgb(70, 77, 77)",fontWeight:"bold"}}>EZblu客服</h4>
                                        <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                            <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                           alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",Width:300}}><a 
                                            style={{}}
                                            >{v.msg}</a></h3>
                                        </div>
                                    </div>    
                                </div>
                            
                        </div>
                        
                        :
                        
                        <div style={{paddingTop:30,width:"100%",display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end"}}> 
                        <div style={{borderRadius:40,display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end"}}>     
                           <div style={{display:"flex",flexDirection:"row"}}>
                                     <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                        <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                        alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",Width:300}}><a 
                                        style={{}}
                                        >{v.msg}</a></h3>
                                    </div>  
                            </div>   
                             
                            <div style={{width:40,height:40,borderRadius:40}}>
                             <img style={{width:"100%",height:"100%"}} src={Kehu}></img>
                            </div>
                            
                          </div>
                       </div> 
                    }

                       
                        </div>
                     </div>
                )
            })}</div>
            <div style={{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
            {/* <Button
            style={{width:200,marginTop:50}}
            type="primary" onClick={startOnclick}>启动链接</Button>
            <Button
            style={{width:200,marginTop:50}}
            type="primary" onClick={clearOnclick}>断开链接</Button> */}
            <Button
            style={{width:200,marginTop:10,alignItems:"flex-end"}}
            type="primary" onClick={sendMessages}>发送消息</Button>

            <InputItem
            clear
            onChange={txt=>setTxt(txt)}
            placeholder="请输入您的信息"
            value={txt}
            >
            </InputItem>
            
            </div>


               
       </div>
        )
}
export default OnlineSystemService
